package com.leyou.user.service.impi;

import com.leyou.common.utils.NumberUtils;
import com.leyou.item.pojo.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import com.leyou.user.utils.CodecUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Log4j2
@Service
public class UserServiceImp implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 发送短信并保存到redis中一份
     *
     * @param phone
     */
    @Override
    public Boolean sendCode(String phone) {

        try {
            //调用工具类,生成随机验证码
            String code = NumberUtils.generateCode(4);
            //调用mq调用发送短信服务
            Map<String, String> map = new HashMap<>();
            map.put("phone", phone);
            map.put("code", code);
            this.amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",map);

            //保存一份数据到redis中
            this.stringRedisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
            log.error("发送信息失败");
            return false;
        }

    }

    /**
     * 校验用户名；和手机号；由于用户名唯一性，输入数据利用通用mapper查询查到就是存在不可用，查不到就是不存在，可用。
     *
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean checkData(String data, Integer type) {
        User user = new User();
        if (type == 1) {
            user.setUsername(data);
        } else if (type == 2) {
            user.setPhone(data);
        }
        int count = this.userMapper.selectCount(user);
        return count == 0;//没查到，返回true；代表可用，
    }

    /**
     * 注册业务
     *
     * @param user
     * @param code
     */
    @Override
    public Boolean saveUser(User user, String code) {
        //首先验证验证码是否正确

        Boolean boo = false;
        String storeCode =  this.stringRedisTemplate.opsForValue().get(user.getPhone());
        if (StringUtils.isNotBlank(storeCode)) {//判断redis中验证码是否为空,设置5分钟消失
            if (storeCode.equals(code)) {//判断验证码与输入的是否一致
                user.setCreated(new Date());
                String salt = CodecUtils.generateSalt();
                user.setSalt(salt);
                user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
                boo = this.userMapper.insert(user) == 1;
                //理论上,保存用户成功之后;把redis验证码删除
                this.stringRedisTemplate.delete(user.getPhone());
                return boo;
            }

        }
        return boo;
    }

    /**
     * 查询用户业务
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User queryUser(String username, String password) {
        //先根据用户姓名查询用户信息，在比较密码是否正确
        User user = new User();
        user.setUsername(username);
        User resultUser = this.userMapper.selectOne(user);
        if (resultUser == null) {
            return null;
        }
        String salt = resultUser.getSalt();
        String pwd = CodecUtils.md5Hex(password, salt);
        if (resultUser.getPassword().equals(pwd)) {
            return resultUser;
        }
        return null;
    }
}
